﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.Threading;

namespace TCPCliente
{
    class Program
    {
        static object   o   = new object();
        static int      x   = 0x00;

        static void Main (string [] args)
        {
            int cant = 1;
            Thread[] threads = new Thread[cant];

            for (int i = 0; i < cant; ++i)
            {
                threads[i] = new Thread(new ThreadStart(clientes));
            }

            for (int i = 0; i < cant; ++i)
            {
                threads[i].Start();
            }
            
            Console.ReadLine    ();
            Console.WriteLine   (x);
            Console.ReadLine    ();
        }

        static void clientes ()
        {
            var start = Environment.TickCount;

            for (int i = 0; ; ++i)
            {
                TcpClient cliente = new TcpClient();
                //cliente.Connect("sm-ftp", 6969);
                cliente.Connect("localhost", 9000);

                using (NetworkStream ns = cliente.GetStream())
                {
                    int @byte = 0;
                    
                    try
                    {
                        var buffRead = new byte[128];

                        var buff = Encoding.ASCII.GetBytes("##,imei:123456789012345,A;");
                        ns.Write(buff, 0, buff.Length);
                        ns.Read(buffRead, 0, 4);
                        Console.WriteLine(Encoding.ASCII.GetString(buffRead));

                        buffRead = new byte[128];

                        buff = Encoding.ASCII.GetBytes("123456789012345;");
                        ns.Write(buff, 0, buff.Length);
                        ns.Read(buffRead, 0, 2);
                        Console.WriteLine(Encoding.ASCII.GetString(buffRead));

                        buff = Encoding.ASCII.GetBytes("imei:377777777777777,tracker,0809231929,13554900601,F,112909.397,A,2234.4669,N,11254.3287,E,0.11,;");
                        ns.Write(buff, 0, buff.Length);

                        lock (o)
                        {
                            while ('s' != (char)(byte)(@byte = ns.ReadByte()))
                                Console.Write((char)(byte)@byte);
                            Console.WriteLine();
                        }
                        
                        Thread.Sleep(1);

                        lock (o)
                            x++;
                    }
                    catch
                    { 
                        //
                    }

                    ns.Close();
                }

                cliente.Close();
            }

            lock (o)
                Console.WriteLine(Environment.TickCount - start);
        }
    }
}
